package com.limm.servlet.register;

import com.limm.dao.register.RegisterDao;
import com.limm.util.DbUtil;
import com.limm.util.Util;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private Map map = new HashMap();
    private String msg = "message";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String varify = request.getParameter("verify");
        //获取session
        HttpSession session = request.getSession();
        String varyCode = session.getAttribute("validation_code").toString();
        if (!varify.equalsIgnoreCase(varyCode)) {
            map.put(msg, "验证码错误");
        } else {
            //进行注册
            register(username, email, password);
        }
        JSONObject json = JSONObject.fromObject(map);
        response.getWriter().print(json.toString());
        DbUtil.close();
    }

    private void register(String username, String email, String password) {
        RegisterDao regDao = new RegisterDao();
        if (regDao.isExistOfEmail(email)) {//邮箱存在，注册失败
            map.put(msg, "该邮箱已被使用！！");
        } else {//邮箱不存在
            regDao.insert(Util.getUUID(),username, password, email,Util.getData());
            map.put(msg, "注册成功");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
